# coding: utf8


from pyecharts.charts import Map, Geo
from pyecharts import options as opts
from pyecharts.globals import ChartType     # , CurrentConfig
import random


class DemoMap:

    @staticmethod
    def map(maptype='china', data_dict: dict = None,
            title='', subtitle='', filename='',
            value_max=12000, value_min=0):
        """
        used for pyecharts Version 1.X.X
        maptype: maptype for pyecharts map. default: 'china'
                 use chinese name for province-, city-, county- level map
        data_dict: dict of (district_name, value), district for name of nations, provinces, counties, cities
                   default: Populations of provinces and cities of china
        title: map title
        subtitle: map subtitle
        filname: html page file name. default: maptype+'_'+title+'.html'
        """
        data = [("广东", 10430.03), ("山东", 9579.31), ("河南", 9402.36), ("四川", 8041.82), ("江苏", 7865.99),
                ("河北", 7185.42), ("湖南", 6568.37), ("安徽", 5950.1), ("浙江", 5442), ("湖北", 5723.77),
                ("广西", 4602.66), ("云南", 4596.6), ("江西", 4456.74), ("辽宁", 4374.63), ("黑龙江", 3831.22),
                ("陕西", 3732.74), ("山西", 3571.21), ("福建", 3552), ("重庆", 2884), ("贵州", 3476.65),
                ("吉林", 2746.22), ("甘肃", 2557.53), ("内蒙古", 2470.63), ("上海", 2301.391), ("台湾", 2316.2),
                ("新疆", 2181.33), ("北京", 1961.2), ("天津", 1293.82), ("海南", 867.15), ("香港", 709.76),
                ("青海", 562.67), ("宁夏", 630.14), ("西藏", 300.21), ("澳门", 55.23)]
        if data_dict:
            data = [(k, v) for k, v in data_dict.items()]
        if not data_dict:
            title = "各省市人口数"
            subtitle = "数据来源：中国统计年鉴（万人）"
        if not filename:
            filename = maptype+'_'+title+'.html'
        if not maptype:
            maptype = 'china'

        (
            Map()
            .add("", data, maptype)
            .set_global_opts(
                title_opts=opts.TitleOpts(
                    title=title,
                    subtitle=subtitle,
                    pos_right="center",
                    pos_top="5%"
                    ),
                visualmap_opts=opts.VisualMapOpts(
                    max_=value_max,
                    min_=value_min,
                    is_piecewise=True
                    ),
                )
            .render(filename)
        )

    @staticmethod
    def county_map():
        counties = (
            Map()
            .add(
                "",
                [['攸县', 1]],
                "株洲",
                label_opts=opts.LabelOpts(is_show=False)
                )
            .set_global_opts(
                title_opts=opts.TitleOpts(title="中国某市区县地图"),
                visualmap_opts=opts.VisualMapOpts(),
                )
            .render("某市区县地图.html")
        )

    @staticmethod
    def city_map():
        """v1.x"""
        city = ['历下区', '市中区', '槐荫区', '天桥区', '历城区', '长清区', '章丘区', '平阴县', '济阳县', '商河县', '莱芜区']
        data = [(i, random.randint(100, 200)) for i in city]
        city_map = (
            Map()
            .add("", data, "济南")
            .set_global_opts(
                title_opts=opts.TitleOpts(title="济南市地图"),
                visualmap_opts=opts.VisualMapOpts(
                    min_=100,
                    max_=200,
                    is_piecewise=True
                    )
                )
            .render(path="济南市地图v1x.html")
        )

    @staticmethod
    def province_map():
        """v1.x"""
        prov_city = ['长沙市', '株洲市', '湘潭市', '衡阳市']
        data_prov_city = [(i, random.randint(100, 200)) for i in prov_city]
        prov_map = (
            Map()
            .add("", data_prov_city, "湖南")
            .set_global_opts(
                title_opts=opts.TitleOpts(title="某省地级市地图"),
                visualmap_opts=opts.VisualMapOpts(
                    min_=100,
                    max_=200,
                    is_piecewise=True
                    )
                )
            .render(path="某省地级市地图v1x.html")
        )

    @staticmethod
    def shandong_map(value=None, max_=None, min_=None):
        """
        v1.x
        problem: can not display html
        """
        import numpy as np
        city = ['济南市', '青岛市', '淄博市', '枣庄市', '东营市', '烟台市', '潍坊市', '济宁市', '泰安市',
                '威海市', '日照市', '临沂市', '德州市', '滨州市', '聊城市', '菏泽市', '莱芜市']
        if value:
            if len(value) != len(city):
                raise ValueError("len(value) != len(city_names)")
        value = value if value else [100-j*5 for j in range(len(city))]
        max_ = max(value) if max_ else max_
        min_ = min(value) if min_ else min_
        data = [(c, v) for c, v in zip(city, value)]
        city_map = (
            Map()
            .add("山东", data_pair=data, maptype='山东')
            .set_global_opts(
                title_opts=opts.TitleOpts(
                    title="山东地图",
                    subtitle="山东",
                    pos_right='center',
                    pos_top="5%"),
                visualmap_opts=opts.VisualMapOpts(max_=max_, min_=min_),
            )
            .render(path="pyecharts_deom_山东地图.html")
            )

    @staticmethod
    def guiyang_map():
        """
        v1.x
        problem: can not display html
        """
        # quxian = ['观山湖区', '云岩区', '南明区', '花溪区', '乌当区', '白云区', '修文县', '息烽县', '开阳县', '清镇市']
        quxian = ['观山湖', '云岩', '南明', '花溪', '乌当', '白云', '修文', '息烽', '开阳', '清镇']
        values = [3, 5, 7, 8, 2, 4, 7, 8, 2, 4]
        map = Map()
        map.add("贵阳", [(x, y) for x, y in zip(quxian, values)], '贵州')
        map.set_global_opts(
            title_opts=opts.TitleOpts(title="贵阳地图", subtitle="贵阳", pos_right='center', pos_top="5%"),
            visualmap_opts=opts.VisualMapOpts(max_=10),
        )
        map.render(path="pyecharts_demo_贵阳地图.html")

    @staticmethod
    def geo_air_quanty():
        """
        # 系列名称，用于 tooltip 的显示，legend 的图例筛选。  series_name: str,
        # 数据项 (坐标点名称)    names：list
        # 数据项 (坐标点值)    value: list
        # Geo 图类型，有 scatter, effectScatter, heatmap, lines 4 种    type: 默认"scatter",
        # 是否选中图例    is_selected: 默认True,
        # 标记图形形状,circle，pin，rect，diamon，roundRect，arrow，triangle    symbol: 默认circle,
        # 标记的大小    symbol_size: 默认12,
        # 系列 label 颜色    color: 默认None,
        # 是否是多段线，在画 lines 图情况下    is_polyline: 默认 False,
        # 是否启用大规模线图的优化，在数据图形特别多的时候（>=5k）可以开启    is_large: 默认 False,
        # 特效尾迹的长度。取从 0 到 1 的值，数值越大尾迹越长。    trail_length:默认 0.2
        # 地图选择，如广东、广州、china,   maptype
        # 不知道什么作用，只知道默认True    is_random
        # 是否开启鼠标缩放和平移漫游。'scale'缩放、'move'平移、'True'都开启    is_roam：默认True
        # 显示图例条    is_visualmap：默认True
        # 图例条范围    visual_range
        # 图例条颜色    visual_text_color
        # 常态下地图的颜色    geo_normal_color
        # 触发下地图的颜色（鼠标放在地图上）    geo_emphasis_color
        # 涟漪的多少，当type="effectScatter"时才有效    effect_scale
        # 显示标签    is_label_show
        # 标签颜色    label_text_color
        # 标签位置（inside，top，bottom，left，right）    label_pos：默认"inside"
        # 边界颜色    border_color
        """
        data = [
            ("青岛市", 80),
            ("海门市", 19), ("鄂尔多斯", 12), ("招远", 12), ("舟山", 12), ("齐齐哈尔", 14), ("盐城", 15),
            ("赤峰", 160), ("青岛", 18), ("乳山", 18), ("金昌", 19), ("泉州", 21), ("莱西", 21),
            ("日照", 21), ("胶南", 22), ("南通", 23), ("拉萨", 24), ("云浮", 24), ("梅州", 25)]
        geo = (
            Geo()
            .add_schema(maptype="china")
            .add(series_name='', data_pair=data, type_=ChartType.HEATMAP)
            .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
            .set_colors(colors='#FF00FF')
            .set_global_opts(
                visualmap_opts=opts.VisualMapOpts(),
                legend_opts=opts.LegendOpts(is_show=False),
                title_opts=opts.TitleOpts(title="全国空气质量热力地图"))
            .render('pyecharts_demo全国空气质量热量地图.html')
        )


class DemoBar:

    @staticmethod
    def bar_label_rotate():
        from pyecharts import options as opts
        from pyecharts.charts import Bar

        c = (
            Bar()
            .add_xaxis(
                [
                 "名字很长的X轴标签1",
                 "名字很长的X轴标签2",
                 "名字很长的X轴标签3",
                 "名字很长的X轴标签4",
                 "名字很长的X轴标签5",
                 "名字很长的X轴标签6",
                ]
                )
            .add_yaxis("商家A", [10, 20, 30, 40, 50, 40])
            .add_yaxis("商家B", [20, 10, 40, 30, 40, 50])
            .set_global_opts(
                xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-15)),
                title_opts=opts.TitleOpts(title="Bar-旋转X轴标签", subtitle="解决标签名字过长的问题"),
                )
            .render("bar_rotate_xaxis_label.html")
        )

    @staticmethod
    def bar_toolbox():
        from pyecharts import options as opts
        from pyecharts.charts import Bar
        from pyecharts.faker import Faker

        c = (
            Bar()
            .add_xaxis(Faker.choose())
            .add_yaxis("商家A", Faker.values())
            .add_yaxis("商家B", Faker.values())
            .set_global_opts(
                title_opts=opts.TitleOpts(title="Bar-显示 ToolBox"),
                toolbox_opts=opts.ToolboxOpts(),
                legend_opts=opts.LegendOpts(is_show=False),
                )
            .render("bar_toolbox.html")
        )

    @staticmethod
    def bar_brush():
        from pyecharts import options as opts
        from pyecharts.charts import Bar
        from pyecharts.faker import Faker

        c = (
            Bar()
            .add_xaxis(Faker.choose())
            .add_yaxis("商家A", Faker.values())
            .add_yaxis("商家B", Faker.values())
            .set_global_opts(
                title_opts=opts.TitleOpts(title="Bar-Brush示例", subtitle="我是副标题"),
                brush_opts=opts.BrushOpts(),
                )
            .render("bar_with_brush.html")
            )

    @staticmethod
    def bar_3d():
        import random
        from pyecharts import options as opts
        from pyecharts.charts import Bar3D
        from pyecharts.faker import Faker


        data = [(i, j, random.randint(0, 12)) for i in range(6) for j in range(24)]
        c = (
            Bar3D()
            .add(
                "",
                [[d[1], d[0], d[2]] for d in data],
                xaxis3d_opts=opts.Axis3DOpts(Faker.clock, type_="category"),
                yaxis3d_opts=opts.Axis3DOpts(Faker.week_en, type_="category"),
                zaxis3d_opts=opts.Axis3DOpts(type_="value"),
                )
            .set_global_opts(
                visualmap_opts=opts.VisualMapOpts(max_=20),
                title_opts=opts.TitleOpts(title="Bar3D-基本示例"),
                )
            .render("bar3d_base.html")
            )

    @staticmethod
    def bar_html():
        from pyecharts.charts import Bar
        # from snapshot_selenium import snapshot as driver
        # from pyecharts.render import make_snapshot

        bar = Bar()

        bar.add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
        bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
        bar.set_global_opts(title_opts=opts.TitleOpts(title="绘图示例"))

        # render 会生成本地 HTML 文件，默认会在当前目录生成 render.html 文件
        # 也可以传入路径参数，如 bar.render("mycharts.html")
        bar.render()

        # make_snapshot(driver, bar.render(), 'render.png')

    @staticmethod
    def bar_png():
        from pyecharts.charts import Bar
        from snapshot_selenium import snapshot as driver
        from pyecharts.render import make_snapshot

        bar = Bar()

        bar.add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
        bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
        bar.set_global_opts(title_opts=opts.TitleOpts(title="绘图示例"))

        make_snapshot(driver, bar.render(), 'render.png')


class DemoTree:

    @staticmethod
    def tree_mpl_objects():
        from pyecharts import options as opts
        from pyecharts.charts import Tree

        """
        Figure 画板
        |
         Axes 坐标系（子图）
        |
        |<-- Axis 坐标轴
        |     |<--  Major Ticks主刻度
        |     |         | <-- Tick Label刻度标签
        |	  |         | <-- Tick Locator刻度定位器
        |     |         | <-- Tick Formatter刻度格式器
        |     |
        |     |<--  Minor Ticks副刻度
        |     |         | <-- Tick Label刻度标签
        |	  |         | <-- Tick Locator刻度定位器
        |     |         | <-- Tick Formatter刻度格式器
        |     |
        |     |<-- Axis Label坐标轴标签
        |     
        |<-- splines边框对象集
        |     |<-- Spine left左端轴线
        |     |<-- Spine right右端轴线
        |     |<-- Spine top顶端轴线
        |     |<-- Spine bottom底端轴线
        |<-- Grid网格
        |<-- Legend图例
        |<-- Text文本
        |<-- Annotation注释
        |<-- Title标题
        |<-- 绘图对象（Line2D, Patch, ...）
        |<-- 色彩板（Colorbar）
        """

        data_matplotlib_objects = [
            {
             'name': 'Figure',
             'children': [
                  {'name': 'Axes',
                   'children': [
                       {'name': 'splines'},
                       {'name': 'Grid'},
                       {'name': 'Lengend'},
                       {'name': 'Text'},
                       {'name': 'Annotation'},
                       {'name': 'Title'},
                       {'name': 'Colorbar'},
                       {'name': 'Patch, Line2D'},
                   ]},
             ]

            }
        ]

        c = (
            Tree()
            .add("", data_matplotlib_objects)
            .set_global_opts(title_opts=opts.TitleOpts(title="Matplotlib Plot Objects"))
            .render("tree_matplotlib_objects.html")
        )
